package com.newx.test.open.xyz2;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Classname FileReceiver
 * @Description TODO
 * @Date 2025/1/9 10:00
 * @Created by yxl
 */
public class FileReceiver {
    private static final int COMMAND_TYPE_FILE = 0x01;
    private static final int BUFFER_SIZE = 1024;

    public static void receiveFile(Socket socket, String outputPath) throws IOException {
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        FileOutputStream fos = new FileOutputStream(outputPath);

        while (true) {
            try {
                // 读取消息头
                int length = dis.readInt(); // Length
                if (length <= 0) break;

                short commandType = dis.readShort(); // Command Type
                if (commandType != COMMAND_TYPE_FILE) {
                    System.out.println("未知命令类型: " + commandType);
                    break;
                }

                // 读取消息体
                byte[] buffer = new byte[length];
                dis.readFully(buffer, 0, length);

                // 读取校验和（可选）
                short receivedChecksum = dis.readShort();
                short calculatedChecksum = checksum(buffer, length);

                if (receivedChecksum == calculatedChecksum) {
                    fos.write(buffer);
                } else {
                    System.out.println("校验和错误");
                    break;
                }
            } catch (EOFException e) {
                System.out.println("文件接收完成");
                break;
            }
        }

        fos.close();
        dis.close();
    }

    // 校验和验证函数（可选）
    private static short checksum(byte[] data, int length) {
        short sum = 0;
        for (int i = 0; i < length; i++) {
            sum += (short) (data[i] & 0xFF);
        }
        return sum;
    }

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8080);
        System.out.println("连接到服务器");

        receiveFile(socket, "F:\\Desktop\\received_file.txt");
        socket.close();
        System.out.println("文件接收完毕");
    }
}
